package demo.dao.Impl;

import demo.dao.AccountDao;
import demo.entity.Account;
import demo.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AccountDaoImpl implements AccountDao {
    @Override
    public Account selectById(Integer id) throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement prepareStatement = connection.prepareStatement("select * from tb_account where id = ?");
        prepareStatement.setInt(1, id);
        ResultSet resultSet = prepareStatement.executeQuery();
        Account qaccount = null;
        while (resultSet.next()) {
            qaccount = new Account(id, resultSet.getString("name"), resultSet.getDouble("money"));
        }
        JDBCUtils.closeAll(prepareStatement, resultSet);
        return qaccount;
    }

    @Override
    public int updateById(Integer fromId, Double money) throws SQLException {
        Connection connection = JDBCUtils.getConnection();
        PreparedStatement prepareStatement = connection.prepareStatement("update tb_account set money = money + ? where id = ?");
        prepareStatement.setDouble(1, money);
        prepareStatement.setInt(2, fromId);
        int result = prepareStatement.executeUpdate();
        JDBCUtils.closeAll(prepareStatement,null);
        return result;
    }
}
